package com.peking.donations.plugins.pay.wx.web.interceptor;

import com.peking.donations.base.util.SequenceUtil;
import com.peking.donations.plugins.pay.wx.service.AuthorizeService;
import com.peking.donations.plugins.pay.wx.utils.GlobalConfigure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * WxJsSdkInterceptor
 * <p>
 * <p>
 * </p>
 *
 * @author Vigor Yuan
 */
public class WxJsSdkInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    AuthorizeService authorizeService;



    @Autowired
    GlobalConfigure globalConfigure;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        if (modelAndView == null ) {
            return;
        }
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = SequenceUtil.getRandomStringByLength(6);
        // url包含完整的请求参数，但不包含#
        String url = request.getRequestURL().toString();

        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }

        String signature = authorizeService.getJssdkSignature(globalConfigure.getAppID().toString(), url, timeStamp,
                nonceStr);
        modelAndView.getModelMap().addAttribute("wx_config_nonceStr", nonceStr);
        modelAndView.getModelMap().addAttribute("wx_config_wxAppId", globalConfigure.getAppID());
        modelAndView.getModelMap().addAttribute("wx_config_timeStamp", timeStamp);
        modelAndView.getModelMap().addAttribute("wx_config_signature", signature);
        modelAndView.getModelMap().addAttribute("globalHostName",globalConfigure.getHostname());
    }
}
